package com.ripservice.config;

import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Configuration;
import org.springframework.messaging.simp.config.MessageBrokerRegistry;
import org.springframework.web.socket.config.annotation.EnableWebSocketMessageBroker;
import org.springframework.web.socket.config.annotation.StompEndpointRegistry;
import org.springframework.web.socket.config.annotation.WebSocketMessageBrokerConfigurer;

/**
 * WebSocket配置类，用于配置WebSocket消息代理和STOMP端点
 *
 * @author rip
 * @version 1.0
 */
@Slf4j
@Configuration
@EnableWebSocketMessageBroker
public class WebSocketConfig implements WebSocketMessageBrokerConfigurer {

    /**
     * 配置消息代理
     * 启用简单消息代理，用于处理/topic前缀的消息
     * 设置应用目的地前缀为/app，客户端发送消息时需要加上此前缀
     *
     * @param registry 消息代理注册器
     */
    @Override
    public void configureMessageBroker(MessageBrokerRegistry registry) {
        // 启用简单消息代理，处理以/topic为前缀的消息
        registry.enableSimpleBroker("/topic");
        // 设置应用目的地前缀，客户端发送消息需要以/app开头
        registry.setApplicationDestinationPrefixes("/app");
        log.info("WebSocket消息代理已配置 - 主题前缀: /topic, 应用前缀: /app");
    }

    /**
     * 注册STOMP协议的端点
     * 添加/ws端点，允许跨域访问，并启用SockJS支持
     *
     * @param registry STOMP端点注册器
     */
    @Override
    public void registerStompEndpoints(StompEndpointRegistry registry) {
        // 注册/ws端点，允许所有域访问，启用SockJS支持
        registry.addEndpoint("/ws")
                .setAllowedOriginPatterns("*")
                .withSockJS();

        // 也添加一个不使用SockJS的端点，方便调试
        registry.addEndpoint("/ws")
                .setAllowedOriginPatterns("*");
        log.info("WebSocket端点已注册 - /ws (支持SockJS和原生WebSocket)");
    }
}